import tkinter as tk
from tkinter import ttk
import matplotlib

matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from collections import deque
import time


class ChartViewer(ttk.Frame):
    """数据图表视图"""

    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller

        # 创建UI
        self.create_widgets()

        # 初始化图表
        self.init_chart()

    def create_widgets(self):
        """创建控件"""
        # 图表控制面板
        control_frame = ttk.Frame(self)
        control_frame.pack(fill=tk.X, padx=5, pady=5)

        ttk.Label(control_frame, text="选择寄存器:").pack(side=tk.LEFT)

        self.reg_var = tk.StringVar()
        self.reg_combo = ttk.Combobox(control_frame, textvariable=self.reg_var, state="readonly")
        self.reg_combo.pack(side=tk.LEFT, padx=5)
        self.reg_combo.bind("<<ComboboxSelected>>", self.update_chart)

        self.add_btn = ttk.Button(control_frame, text="添加图表", command=self.add_chart)
        self.add_btn.pack(side=tk.LEFT, padx=5)

        self.clear_btn = ttk.Button(control_frame, text="清除图表", command=self.clear_chart)
        self.clear_btn.pack(side=tk.LEFT, padx=5)

        # 图表容器
        self.chart_frame = ttk.Frame(self)
        self.chart_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # 初始化图表
        self.fig = Figure(figsize=(10, 4), dpi=100)
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.chart_frame)
        self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)

        # 数据线
        self.lines = {}

    def init_chart(self):
        """初始化图表"""
        self.ax.set_title("寄存器值实时监控")
        self.ax.set_xlabel("时间")
        self.ax.set_ylabel("值")
        self.ax.grid(True)
        self.fig.tight_layout()

        # 更新寄存器列表
        self.update_register_list()

    def update_register_list(self):
        """更新寄存器下拉列表"""
        registers = self.controller.get_registers()
        reg_list = [f"0x{reg.address:04X} - {reg.name}" for reg in registers]
        self.reg_combo['values'] = reg_list
        if reg_list:
            self.reg_var.set(reg_list[0])

    def add_chart(self):
        """添加新的图表"""
        selected = self.reg_var.get()
        if not selected:
            return

        # 提取寄存器地址
        address_hex = selected.split(" ")[0]
        address = int(address_hex, 16)

        # 获取寄存器
        reg = self.controller.get_register(address)
        if not reg:
            return

        # 添加数据线
        if address not in self.lines:
            line, = self.ax.plot([], [], label=reg.name)
            self.lines[address] = line
            self.ax.legend()
            self.canvas.draw()

    def clear_chart(self):
        """清除所有图表"""
        self.lines.clear()
        self.ax.clear()
        self.ax.set_title("寄存器值实时监控")
        self.ax.set_xlabel("时间")
        self.ax.set_ylabel("值")
        self.ax.grid(True)
        self.canvas.draw()

    def update_chart(self, event=None):
        """更新图表数据"""
        if not self.lines:
            return

        # 清空图表
        self.ax.clear()
        self.ax.set_title("寄存器值实时监控")
        self.ax.set_xlabel("时间 (秒)")
        self.ax.set_ylabel("值")
        self.ax.grid(True)

        # 获取历史数据
        for address, line in self.lines.items():
            history = self.controller.get_history(address)
            if not history:
                continue

            # 获取寄存器信息
            reg = self.controller.get_register(address)

            # 提取数据
            timestamps, values = zip(*history)
            rel_times = [ts - timestamps[0] for ts in timestamps]

            # 重新绘制
            new_line, = self.ax.plot(rel_times, values, label=reg.name)
            self.lines[address] = new_line

        # 添加图例
        if self.lines:
            self.ax.legend(loc='upper right')

        # 刷新画布
        self.canvas.draw()
        